package com.alibaba.otter.node.etl.load.loader.mq.rabbit.serializer;

import com.alibaba.otter.node.etl.load.loader.mq.rabbit.exception.MqSerializeException;
import lombok.Getter;
import lombok.Setter;

import java.nio.charset.Charset;

@SuppressWarnings("unchecked")
public class PlainTextSerializer implements Serializer {

    @Getter
    @Setter
    private Charset charset;

    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return null;
        }
        return object.toString().getBytes(charset);
    }

    @Override
    public <T> T deserialize(byte[] content, Class<T> targetClass) {
        if (targetClass != String.class) {
            throw new MqSerializeException("消息类型不是String，不能使用PlainTextSerializer");
        }
        return (T) new String(content, charset);
    }
}
